import time
from machine import Pin, FPIOA PWM
from libs.myuart import myuart

class Button_LED_Module:
    def __init__(self):
        self.fpioa = FPIOA()
        self._init_fpioa()
        self._init_leds()
        self._init_button()
        self.last_press_time = 0
        self.button_last_state = 0
        self.debounce_delay = 200  # 消抖时间 (ms)
        self.photo_led = self.LED_G  # 默认提示用LED

    def _init_fpioa(self):
        self.fpioa.set_function(62, FPIOA.GPIO62)  # 红灯
        self.fpioa.set_function(20, FPIOA.GPIO20)  # 绿灯
        self.fpioa.set_function(63, FPIOA.GPIO63)  # 蓝灯
        self.fpioa.set_function(53, FPIOA.GPIO53)  # 按键

    def _init_leds(self):
        self.LED_R = Pin(62, Pin.OUT, pull=Pin.PULL_NONE, drive=7)
        self.LED_G = Pin(20, Pin.OUT, pull=Pin.PULL_NONE, drive=7)
        self.LED_B = Pin(63, Pin.OUT, pull=Pin.PULL_NONE, drive=7)

        self.LED_R.high()
        self.LED_G.high()
        self.LED_B.high()

    def _init_button(self):
        self.button = Pin(53, Pin.IN, Pin.PULL_DOWN)

    def button_handler(self,str):
        current_time = time.ticks_ms()
        button_state = self.button.value()

        if button_state == 1 and self.button_last_state == 0:  # 检测上升沿
            if current_time - self.last_press_time > self.debounce_delay:
                self.photo_led.low()    # 点亮 LED
                time.sleep_ms(20)
                myuart.uart_send(str)
                print(str)
                self.photo_led.high()   # 熄灭 LED
                self.last_press_time = current_time

        self.button_last_state = button_state

    def set_photo_led(self, color):
        """
        设置哪个 LED 用作提示灯：'R'、'G' 或 'B'
        """
        if color == 'R':
            self.photo_led = self.LED_R
        elif color == 'G':
            self.photo_led = self.LED_G
        elif color == 'B':
            self.photo_led = self.LED_B

mykey=Button_LED_Module()
# 示例使用（主文件中）
# from Button_LED_Module import Button_LED_Module
# led_module = Button_LED_Module()
# while True:
#     led_module.button_handler()
